package com.shqcjd.sinopecdemomobile.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.KnowledgeBean;
import com.shqcjd.sinopecdemomobile.model.pojo.PopKnowledgeBean;
import com.shqcjd.sinopecdemomobile.ui.activity.UploadActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.KnowledgeAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.KnowledgePopAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseFragment;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class KnowledgeFragment extends BaseFragment {
    @BindView(R.id.rv_knowledge)
    RecyclerView rvKnowledge;
    @BindView(R.id.sr_knowledge)
    SwipeRefreshLayout srKnowledge;
    @BindView(R.id.et_knowledge_search)
    EditText etKnowledgeSearch;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.rl_knowledge_upload)
    RelativeLayout rlKnowledgeUpload;


    private KnowledgeAdapter knowledgeAdapter;
    private Context context;
    private View contentView;
    private int page = 1;
    private String strSearch = "";
    private int total;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private List<KnowledgeBean.ListBean> adapterList = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_knowledge;
    }

    public static KnowledgeFragment newInstance() {
        return new KnowledgeFragment();
    }

    @Override
    public void init() {
        super.init();
        context = getActivity();
    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        etKnowledgeSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                strSearch = s.toString();
                refreshData();
            }
        });

        srKnowledge.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        rlKnowledgeUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, UploadActivity.class);
                startActivity(it);
            }
        });
        refreshData();
    }

    private void refreshData() {
        refreshOrLoadMore();
        srKnowledge.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        adapterList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore() {
        if (knowledgeAdapter != null) {
            knowledgeAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getData(int p) {
        ApiService.getKnowledgeList(p, Config.PAGE_TOTAL, strSearch)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<KnowledgeBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<KnowledgeBean> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            total = retData.data.total;
                            adapterList.addAll(retData.data.list);
                            if (knowledgeAdapter == null) {
                                rvKnowledge.setLayoutManager(new WrapContentLinearLayoutManager(context));
                                knowledgeAdapter = new KnowledgeAdapter(adapterList, context);
                                rvKnowledge.setAdapter(knowledgeAdapter);

                                knowledgeAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                    @Override
                                    public void onLoadMoreRequested() {
                                        int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                                        if (page >= pageSize) {
                                            rvKnowledge.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    knowledgeAdapter.loadMoreEnd();
                                                }
                                            });
                                        } else {
                                            loadMoreData();
                                        }
                                    }
                                });
                            }
                            if (isRefreshOrLoadMore == 1) {
                                page = page + 1;
                                knowledgeAdapter.loadMoreComplete();
                            }
                            knowledgeAdapter.notifyDataSetChanged();
                        }
                        srKnowledge.setRefreshing(false);
                        if(adapterList.size()>0){
                            rlIsnull.setVisibility(View.GONE);
                        }else{
                            rlIsnull.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        srKnowledge.setRefreshing(false);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srKnowledge.setRefreshing(false);
                    }
                });
    }


    /**
     * 暂时不用
     * @param view
     */
    private void showPopupWindow(ViewGroup view) {
        if(contentView!=null){
            contentView.setVisibility(View.VISIBLE);
            return;
        }
        contentView = LayoutInflater.from(context).inflate(
                R.layout.pop_knowledge, view, false);
        List stateList = new ArrayList<String>();
        stateList.add("全部");
        stateList.add("设备类型一");
        stateList.add("设备类型二");
        stateList.add("设备类型三");
        view.addView(contentView);
        RelativeLayout rl = contentView.findViewById(R.id.rl);
        LinearLayout ll_pop_content = contentView.findViewById(R.id.ll_pop_content);
        Spinner sp_pop_knowledge_type = contentView.findViewById(R.id.sp_pop_knowledge_type);
        Button btn_pop_reset = contentView.findViewById(R.id.btn_pop_reset);
        Button btn_pop_commit = contentView.findViewById(R.id.btn_pop_commit);
        RecyclerView rv_pop_knowledge = contentView.findViewById(R.id.rv_pop_knowledge);
        List<String> mList = new ArrayList<>();
        mList.add("检修");
        mList.add("轴承");
        mList.add("震动");
        mList.add("轴承");
        mList.add("检修");
        mList.add("轴承");
        mList.add("震动");
        mList.add("轴承");
        List<PopKnowledgeBean> pList = new ArrayList<>();
        rv_pop_knowledge.setLayoutManager(new GridLayoutManager(context, 3));
        for(int i=0; i<mList.size(); i++){
            pList.add(new PopKnowledgeBean(mList.get(i), false));
        }
        KnowledgePopAdapter knowledgePopAdapter = new KnowledgePopAdapter(pList,context);
        rv_pop_knowledge.setAdapter(knowledgePopAdapter);

        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentView.setVisibility(View.GONE);
            }
        });

        ll_pop_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //重置
        btn_pop_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sp_pop_knowledge_type.setSelection(0);
                knowledgePopAdapter.resetCheckList();
            }
        });

        //确定
        btn_pop_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<PopKnowledgeBean> data = knowledgePopAdapter.getMyData();
                String str = "";
                for(int i=0; i<data.size(); i++){
                    if(data.get(i).isCheck){
                        str += data.get(i).name;
                    }
                }
                Toast.makeText(context, stateList.get(sp_pop_knowledge_type.getSelectedItemPosition())+"--"+str,Toast.LENGTH_SHORT).show();
                contentView.setVisibility(View.GONE);
            }
        });

        ArrayAdapter stateAdapter = new ArrayAdapter<String>(context, R.layout.item_spinner, stateList);
        stateAdapter.setDropDownViewResource(R.layout.item_spinner);
        sp_pop_knowledge_type.setAdapter(stateAdapter);
    }
}
